<?php
/**
 * Created by PhpStorm.
 * User: xsp
 * Date: 2018/4/15
 * Time: 19:57
 */namespace frontend\controllers;


use backend\models\Product;
use frontend\models\Cart;
use yii\web\Controller;

class CartController extends CommonController
{

    public $layout = false;
    public function actionIndex()
    {
        $this->layout = 'layout1';
        $session = \Yii::$app->session;
        if(!$session['user'])
        {
            return $this->redirect(['member/login']);
        }
        $uid = $session['user']['uid'];
        $carts = Cart::find()->where(['userid'=>$uid])->asArray()->all();
        $data = [];
        foreach ($carts as $key=>$pro)
        {
            $product = Product::find()->where(['productid'=>$pro['productid']])->one();
            $data[$key]['title'] = $product->title;
            $data[$key]['cover'] = $product->cover;
            $data[$key]['productnum'] = $pro['productnum'];
            $data[$key]['price'] = $pro['price'];
            $data[$key]['productid'] = $pro['productid'];
            $data[$key]['cartid'] = $pro['cartid'];
        }
        return $this->render('index',['data'=>$data]);
    }
    public function actionAdd()
    {
        $session = \Yii::$app->session;
        if(!$session['user'])
        {
            return $this->redirect(['member/login']);
        }
        if (\Yii::$app->request->isPost)
        {
            $post = \Yii::$app->request->post();
            $uid = $session['user']['uid'];
            $data = Cart::find()->where(['userid'=>$uid,'productid'=>$post['productid']])->one();
            if(!$data)
            {
                $cart = new Cart();
                $cart->userid = $uid;
                $cart->productid = $post['productid'];
                $cart->productnum = 1;
                $cart->price = $post['price'];
                $cart->createtime = time();
                $cart->save();
            }else{
                $data::updateAll(['productnum'=>$data['productnum']+1]);
            }
        }
        return $this->redirect(['cart/index']);
    }
    public function actionMod()
    {
        $cartid = \Yii::$app->request->get('cartid');
        $productnum = \Yii::$app->request->get('productnum');

        Cart::updateAll(['productnum'=>$productnum],['cartid'=>$cartid]);
    }
    public function actionDel()
    {
        $cartid = \Yii::$app->request->get('cartid');
        Cart::deleteAll(['cartid'=>$cartid]);
        return $this->redirect(['cart/index']);
    }
}